package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时人物类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 处理待支付超时的订单
     * 每分钟都处理一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void resolveTimedOutOrder(){
        log.info("支付超时订单处理...");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

      List<Orders> ordersList= orderMapper.resovleOrders(Orders.PENDING_PAYMENT,time);


      if (ordersList!=null && ordersList.size()>0){
          for (Orders orders : ordersList) {
              threadPoolTaskExecutor.execute(new Runnable() {
                  @Override
                  public void run() {
                      orders.setStatus(Orders.CANCELLED);
                      orders.setCancelTime(LocalDateTime.now());
                      orders.setCancelReason("支付已超时，自动取消订单");
                      //加入这个操作数据库的时间需要5分钟，但是每一分钟就会执行一次update
                      //此时使用线程池就能提高效率
                      orderMapper.update(orders);
                  }
              });

          }
      }
    }


    /**
     * 每隔一小时，就处理派送中的订单
     * 订单派送一个小后，自动将派送中的订单的状态设置为已完成
     * 每天凌晨1点处理
     *
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void resolveDeliveryOrders(){

        log.info("派送一个小时后的订单处理...");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList=orderMapper.resovleOrders(Orders.DELIVERY_IN_PROGRESS,time);

        if (ordersList!=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }


}
